<template>
	<div class="todo-container">
		<div class="todo-wrap">
			<!-- 给Header的vc绑定了一个add-todo事件，若事件被触发，则：addTodo函数被调用 -->
			<Header @add-todo="addTodo"/>
			<List :todos="todos"/>
			<Footer v-show="todos.length" :clearAllDone="clearAllDone" :todos="todos" :checkAll="checkAll"/>
		</div>
	</div>
</template>

<script>
	import Header from './components/Header'
	import List from './components/List'
	import Footer from './components/Footer'

	export default {
		name: 'App',
		components:{Header,List,Footer},
		data(){
			return{
				todos:JSON.parse(localStorage.getItem('todos')) || []
			}
		},
		methods: {
			//添加一个todo
			addTodo(todoObj){
				this.todos.unshift(todoObj)
			},
			//删除一个todo
			deleteTodo(id){
				this.todos = this.todos.filter(todoObj => todoObj.id !== id)
			},
			//勾选 or 取消勾选
			checkTodo({id,done}){
				const targetTodo = this.todos.find((todoObj)=>{
					// console.log('@')
					return todoObj.id === id
				})
				targetTodo.done = done
			},
			//清除所有已完成
			clearAllDone(){
				this.todos = this.todos.filter(todoObj => !todoObj.done )
			},
			//全选 or 取消全选
			checkAll(done){
				this.todos.forEach((todo)=>{
					todo.done = done
				})
			}
		},
		watch:{
			todos:{
				deep:true,
				handler(value){
					console.log('todos变化了')
					localStorage.setItem('todos',JSON.stringify(value))
				}
			}
		},
		mounted() {
			this.$bus.$on('delete-todo',this.deleteTodo)
			this.$bus.$on('check-todo',this.checkTodo)
		},
		beforeDestroy() {
			this.$bus.$off('delete-todo')
			this.$bus.$off('check-todo')
		},
	}
</script>
